package com.myblog.runner;

import com.myblog.Utils.RedisCache;
import com.myblog.domain.contants.GlobalConstants;
import com.myblog.domain.entity.Article;
import com.myblog.mapper.ArticleMapper;
import com.myblog.services.ArticleService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
public class ArticleViewRunner implements CommandLineRunner {
    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private RedisCache redisCache;
    @Override
    public void run(String... args) throws Exception {
        //从数据库中查出view然后放到redis中
        List<Article> articleList = articleMapper.selectList(null);
        //view id-> view count
        Map<String, Integer> viewCountMap = articleList.stream()
                .collect(Collectors.toMap(article -> article.getId().toString(), article -> Math.toIntExact(article.getViewCount())));
        redisCache.setCacheMap(GlobalConstants.VIEWCOUNT_MAP_NAME,viewCountMap);
    }
}
